package xyh

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func httpRequest(path string, params url.Values, requestData interface{}) (*[]byte, error) {
	client := &http.Client{}
	var request *http.Request

	url := fmt.Sprintf(`%s/%s?%s`, Conf.BaseURL, path, params.Encode())
	if requestData == nil {
		request, _ = http.NewRequest("GET", url, nil)
	} else {
		d, _ := json.Marshal(requestData)
		request, _ = http.NewRequest("POST", url, bytes.NewReader(d))
		request.Header.Set("Content-Type", "application/json")
	}

	resp, err := client.Do(request)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return nil, errors.New("Server error: " + resp.Status)
	}

	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return &content, nil
}

// http request，带凭证
func HttpRequest(path string, params url.Values, requestData interface{}) (*[]byte, error) {
	token, err := RefreshAccessToken()
	if err != nil {
		return nil, err
	}
	params.Add("access_token", *token)
	return httpRequest(path, params, requestData)
}
